package com.ys.nms.module.business.controller.admin.redData;

import com.ys.nms.module.business.libreApi.config.LibreNmsConfigFactory;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/business/rrdback")
@RequiredArgsConstructor
@CrossOrigin(origins = "*") // 允许跨域访问
public class RrdDataController {

    private final RrdToolReader rrdToolReader;
    private final RrdToolReaderForWindows rrdToolReaderForWindows;
    private final LibreNmsConfigFactory configFactory;

    /**
     * 获取设备RRD数据
     */
    @GetMapping("/data/{deviceIp}")
    public ResponseEntity<RrdQueryResult> getRrdData(
            @PathVariable String deviceIp,
            @RequestParam(defaultValue = "poller-perf-availability.rrd") String rrdFile,
            @RequestParam(defaultValue = "now-1h") String startTime,
            @RequestParam(defaultValue = "now") String endTime) {

        log.info("查询RRD数据 - 设备: {}, 文件: {}, 时间范围: {} 到 {}",
                deviceIp, rrdFile, startTime, endTime);
        RrdQueryResult result;
        if (isLocalProfile()) {
            result = rrdToolReaderForWindows.queryRrdData(deviceIp, rrdFile, startTime, endTime);
        } else {
            result = rrdToolReader.queryRrdData(deviceIp, rrdFile, startTime, endTime);
        }


        if (result.getSuccess()) {
            log.info("查询成功，获取到 {} 个数据点，其中 {} 个有效",
                    result.getTotalPoints(), result.getValidPoints());
            return ResponseEntity.ok(result);
        } else {
            log.warn("查询失败: {}", result.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 使用JSON body查询RRD数据
     */
    @PostMapping("/data")
    public ResponseEntity<RrdQueryResult> getRrdData(@RequestBody RrdQueryParams params) {
        log.info("查询RRD数据 - 参数: {}", params);
        RrdQueryResult result;
        if (isLocalProfile()) {
            result = rrdToolReaderForWindows.queryRrdData(params);
        } else {
            result = rrdToolReader.queryRrdData(params);
        }

        if (result.getSuccess()) {
            return ResponseEntity.ok(result);
        } else {
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 获取设备可用的RRD文件列表
     */
    @GetMapping("/files/{deviceIp}")
    public ResponseEntity<Map<String, Object>> getRrdFiles(@PathVariable String deviceIp) {
        log.info("获取设备 {} 的RRD文件列表", deviceIp);

        if (isLocalProfile()) {
            if (!rrdToolReaderForWindows.isDeviceAvailable(deviceIp)) {
                return ResponseEntity.badRequest().body(Map.of(
                        "success", false,
                        "message", "设备不存在或无法访问: " + deviceIp
                ));
            }
        } else {
            if (!rrdToolReader.isDeviceAvailable(deviceIp)) {
                return ResponseEntity.badRequest().body(Map.of(
                        "success", false,
                        "message", "设备不存在或无法访问: " + deviceIp
                ));
            }
        }


        List<String> files;
        if (isLocalProfile()) {
            files = rrdToolReaderForWindows.getAvailableRrdFiles(deviceIp);
        } else {
            files = rrdToolReader.getAvailableRrdFiles(deviceIp);
        }


        return ResponseEntity.ok(Map.of(
                "success", true,
                "deviceIp", deviceIp,
                "files", files,
                "count", files.size()
        ));
    }

    /**
     * 获取有效数据点（过滤NaN值）
     */
    @GetMapping("/data/{deviceIp}/valid")
    public ResponseEntity<Map<String, Object>> getValidRrdData(
            @PathVariable String deviceIp,
            @RequestParam(defaultValue = "poller-perf-availability.rrd") String rrdFile,
            @RequestParam(defaultValue = "now-1h") String startTime,
            @RequestParam(defaultValue = "now") String endTime) {

        RrdQueryResult result;
        if (isLocalProfile()) {
            result = rrdToolReaderForWindows.queryRrdData(deviceIp, rrdFile, startTime, endTime);
        } else {
            result = rrdToolReader.queryRrdData(deviceIp, rrdFile, startTime, endTime);
        }


        if (!result.getSuccess()) {
            return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", result.getMessage()
            ));
        }

        List<RrdDataPoint> validData;
        if (isLocalProfile()) {
            validData = rrdToolReaderForWindows.getValidDataPoints(result);
        } else {
            validData = rrdToolReader.getValidDataPoints(result);
        }


        return ResponseEntity.ok(Map.of(
                "success", true,
                "deviceIp", deviceIp,
                "rrdFile", rrdFile,
                "totalPoints", result.getTotalPoints(),
                "validPoints", validData.size(),
                "data", validData,
                "timeRange", startTime + " to " + endTime
        ));
    }

    /**
     * 检查设备是否可用
     */
    @GetMapping("/devices/{deviceIp}/status")
    public ResponseEntity<Map<String, Object>> checkDeviceStatus(@PathVariable String deviceIp) {
        boolean isAvailable = rrdToolReader.isDeviceAvailable(deviceIp);

        return ResponseEntity.ok(Map.of(
                "deviceIp", deviceIp,
                "available", isAvailable,
                "message", isAvailable ? "设备可访问" : "设备不存在或无法访问"
        ));
    }

    /**
     * 批量查询多个设备的数据
     */
    @PostMapping("/batch-data")
    public ResponseEntity<Map<String, Object>> getBatchRrdData(@RequestBody List<RrdQueryParams> paramsList) {
        log.info("批量查询 {} 个设备的RRD数据", paramsList.size());

        List<RrdQueryResult> results = paramsList.stream()
                .map(rrdToolReader::queryRrdData)
                .collect(java.util.stream.Collectors.toList());

        long successCount = results.stream().filter(RrdQueryResult::getSuccess).count();

        return ResponseEntity.ok(Map.of(
                "success", true,
                "totalQueries", paramsList.size(),
                "successfulQueries", successCount,
                "failedQueries", paramsList.size() - successCount,
                "results", results
        ));
    }

    /**
     * 获取数据统计信息
     */
    @GetMapping("/data/{deviceIp}/stats")
    public ResponseEntity<Map<String, Object>> getDataStats(
            @PathVariable String deviceIp,
            @RequestParam(defaultValue = "poller-perf-availability.rrd") String rrdFile,
            @RequestParam(defaultValue = "now-1h") String startTime,
            @RequestParam(defaultValue = "now") String endTime) {


        RrdQueryResult result;
        if (isLocalProfile()) {
            result = rrdToolReaderForWindows.queryRrdData(deviceIp, rrdFile, startTime, endTime);
        } else {
            result = rrdToolReader.queryRrdData(deviceIp, rrdFile, startTime, endTime);
        }


        if (!result.getSuccess()) {
            return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", result.getMessage()
            ));
        }

        List<RrdDataPoint> validData;

        validData = rrdToolReader.getValidDataPoints(result);

        if (validData.isEmpty()) {
            return ResponseEntity.ok(Map.of(
                    "success", true,
                    "message", "没有有效数据",
                    "totalPoints", result.getTotalPoints(),
                    "validPoints", 0
            ));
        }

        // 计算统计信息
        double min = validData.stream().mapToDouble(RrdDataPoint::getValue).min().orElse(0);
        double max = validData.stream().mapToDouble(RrdDataPoint::getValue).max().orElse(0);
        double avg = validData.stream().mapToDouble(RrdDataPoint::getValue).average().orElse(0);
        double sum = validData.stream().mapToDouble(RrdDataPoint::getValue).sum();

        return ResponseEntity.ok(Map.of(
                "success", true,
                "deviceIp", deviceIp,
                "rrdFile", rrdFile,
                "timeRange", startTime + " to " + endTime,
                "totalPoints", result.getTotalPoints(),
                "validPoints", validData.size(),
                "stats", Map.of(
                        "min", min,
                        "max", max,
                        "average", avg,
                        "sum", sum,
                        "minFormatted", String.format("%.6f", min),
                        "maxFormatted", String.format("%.6f", max),
                        "averageFormatted", String.format("%.6f", avg)
                )
        ));
    }

    public boolean isLocalProfile() {
        String activeProfile = configFactory.getActiveProfile();
        if (activeProfile.equals("local")) {
            return true;
        } else {
            return false;
        }
    }

}